package com.education.project.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.education.project.model.SysConfig;
import com.education.project.service.SysConfigService;

@Controller
@RequestMapping("/system/config")
public class SysConfigController {
	@Autowired
	public SysConfigService sysConfigService;
	
	@GetMapping("/index")
	public String getIndexPage() {
		return "sysconfig";
	}
	
	@PostMapping("/index")
	@ResponseBody
	public List<SysConfig> getAllConfig() {
		return sysConfigService.getAllSysConfig();
	}
	
	@PostMapping("/add")
	@ResponseBody
	public Map<String,Object> addConfig(
			@Valid SysConfig sysConfig,
			BindingResult binder) {
		Map<String,Object> result = new HashMap<String,Object>();
		if(binder.hasErrors()) {
			FieldError fieldError = binder.getFieldErrors().get(0);
			result.put("success", false);
			result.put("message", fieldError.getDefaultMessage());
			return result;
		}
		sysConfigService.saveSysConfig(sysConfig);
		result.put("success", true);
		return result;
	}
	
	@PostMapping("/update")
	@ResponseBody
	public Map<String,Object> updateConfig(
			@Valid SysConfig sysConfig,
			BindingResult binder) {
		Map<String,Object> result = new HashMap<String,Object>();
		if(binder.hasErrors()) {
			FieldError fieldError = binder.getFieldErrors().get(0);
			result.put("success", false);
			result.put("message", fieldError.getDefaultMessage());
			return result;
		}
		sysConfigService.updateSysConfig(sysConfig);
		result.put("success", true);
		return result;
	}
	
	@PostMapping("/delete/{id}")
	@ResponseBody
	public Map<String,Object> deleteConfig(@PathVariable("id") String configname) {
		Map<String,Object> result = new HashMap<String,Object>();
		sysConfigService.deleteSysConfig(configname);
		result.put("success", true);
		return result;
	}
}
